﻿using System.Transactions;
using FluentNHibernate;
using MadMediaManager.Core.Interfaces.DataAccess;
using MadMediaManager.DataAccess.Database;
using NHibernate;
using NUnit.Framework;

namespace MadMediaManager.DataAccess.Tests.Repositories
{
    public abstract class BaseRepositoryTest
    {
        private TransactionScope _scope;
        private static ISessionSource _source;
        
        private const string CONNECTION_STRING = "DataSource=MadMediaManager.sdf";

        private ISession _session;
        protected IDbContext DbContext { get; private set; }

        [TestFixtureSetUp]
        public virtual void TestFixtureSetUp()
        {
            if (_source != null) return;

            var configuration = new NHiberanteConfigurationPropertiesFactory(DatabaseType.SqlCe40, CONNECTION_STRING, true);
            var creator = new SqlCeDatabaseCreator(CONNECTION_STRING).Delete().Create();
            _source = SessionSourceBuilder.Build(configuration.Properties, "MadMediaManager.DataAccess.dll");
            creator.Script(_source.Configuration);
        }

        [TestFixtureTearDown]
        public virtual void TestFixtureTearDown()
        {
            DbContext.Dispose();
        }

        [SetUp]
        public virtual void SetUp()
        {
            _scope = new TransactionScope();
            _session = _source.CreateSession();
            DbContext = new NHibernateDbContext(_session);
        }

        [TearDown]
        public virtual void TearDown()
        {
            _session = null;
            DbContext.Dispose();
            _scope.Dispose();
        }

        protected void FlushAndClear()
        {
            _session.Flush();
            _session.Clear();
        }
    }
}
